/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.application.chiettinhdienluc.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActivityOptions;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Build.VERSION_CODES;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.application.chiettinhdienluc.BuildConfig;
import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.db.HinhAnhChiTietDataSource;
import com.application.chiettinhdienluc.dialog.ConfirmDialog;
import com.application.chiettinhdienluc.model.HinhAnhChiTietModel;
import com.application.chiettinhdienluc.rsclient.NetClientPost;
import com.application.chiettinhdienluc.utils.ImageOptionsUtils;
import com.application.chiettinhdienluc.utils.Utils;

/**
 * The main fragment that powers the ImageGridActivity screen. Fairly straight forward GridView
 * implementation with the key addition being the ImageWorker class w/ImageCache to load children
 * asynchronously, keeping the UI nice and smooth and caching thumbnails for quick retrieval. The
 * cache is retained over configuration changes like orientation change so the images are populated
 * quickly if, for example, the user rotates the device.
 */

public class ImageGridActivity extends FragmentActivity {
	private static final String TAG = "ImageGridActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getSupportFragmentManager().findFragmentByTag(TAG) == null) {
			final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
			ft.add(android.R.id.content, new ImageGridFragment(), TAG);
			ft.commit();
		}
		
		
	}

	public static class ImageGridFragment extends Fragment implements AdapterView.OnItemClickListener{
		private static final String TAG = "ImageGridFragment";
		private static final String IMAGE_CACHE_DIR = "thumbs";

		private int mImageThumbSize;
		private int mImageThumbSpacing;
		private ImageAdapter mAdapter;

//		private Button btn_takepicture;
		private File mPhotoCapturedFile;
		
		private String folderPath = GlobalData.sdcardPath + "/ChietTinh";

		static public ArrayList<String> arrPathImgs = new ArrayList<String>();
		/**
		 * Empty constructor as per the Fragment documentation
		 */
		public ImageGridFragment() {}
		private AQuery mAQ;
		
		private int mYear = 1980;
		private int mMonth = 1;
		private int mDay = 1;
		private int mcur_Year;
		
		private Bitmap mBitmap;
		private ConfirmDialog mDialogDeleteImg;
		
		private GridView mGridView;
		
		private boolean UpdateListenerIsRegistered = false;
		private UpdateListener listener = null;

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setHasOptionsMenu(true);

			mAQ = new AQuery(MainApplication.getAppContext());
			
			mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
			mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);

			mAdapter = new ImageAdapter(getActivity(), mAQ, arrPathImgs);
		}

		@SuppressLint("NewApi")
		@Override
		public View onCreateView(
				LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

			final View v = inflater.inflate(R.layout.image_grid_fragment, container, false);
			mGridView = (GridView) v.findViewById(R.id.gridView);
			mGridView.setAdapter(mAdapter);
			mGridView.setOnItemClickListener(this);
//			mGridView.setOnItemLongClickListener(this);
			mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
				@Override
				public void onScrollStateChanged(AbsListView absListView, int scrollState) {
					// Pause fetcher to ensure smoother scrolling when flinging
				}

				@Override
				public void onScroll(AbsListView absListView, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
				}
			});
			
			registerForContextMenu(mGridView);
			
			tvhint = (TextView)v.findViewById(R.id.tvDeleteHint);

//			btn_takepicture = (Button)v.findViewById(R.id.btn_takepicture);
//			btn_takepicture.setOnClickListener(new View.OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					// TODO Auto-generated method stub
////					takePhoto();
//					takePhoto1();
//				}
//			});
			
//			btn_takepicture.setEnabled(GlobalData.globalChietTinh.get_Id() > 0);

			// This listener is used to get the final width of the GridView and then calculate the
			// number of columns and the width of each column. The width of each column is variable
			// as the GridView has stretchMode=columnWidth. The column width is used to set the height
			// of each view so we get nice square thumbnails.
			mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
					new ViewTreeObserver.OnGlobalLayoutListener() {
						@Override
						public void onGlobalLayout() {
//							if (mAdapter.getNumColumns() == 0) 
							{
								int fullWidth = mGridView.getWidth();
								int itemWidth = mImageThumbSize + mImageThumbSpacing;
								
								final int numColumns = (int) Math.floor(mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));
								
								if (numColumns > 0) {
									final int columnWidth = (mGridView.getWidth() / numColumns) - mImageThumbSpacing;
//									mAdapter.setNumColumns(numColumns);
//									mAdapter.setItemHeight(columnWidth);
									mAdapter.setItemHeight(mImageThumbSize);
									if (BuildConfig.DEBUG) {
										Log.d(TAG, "onCreateView - numColumns set to " + numColumns);
									}
									if (Utils.hasJellyBean()) {
										mGridView.getViewTreeObserver()
										.removeOnGlobalLayoutListener(this);
									} else {
										mGridView.getViewTreeObserver()
										.removeGlobalOnLayoutListener(this);
									}
								}
							}
						}
					});

			return v;
		}
		
		@Override
		public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
			
			if(menuInfo != null) {
				mPos = ((AdapterView.AdapterContextMenuInfo)menuInfo).position;				
			}
			else
				return;
			
			Log.i("trang thai ho so", GlobalData.globalChietTinh.get_TrangThaiHoSo() );
			
			
			if (GlobalData.globalChietTinh.get_TrangThaiHoSo().equalsIgnoreCase("3")) {
				
				HinhAnhChiTietModel ha = GlobalData.HinhAnhList.get(mPos);
				
				if(ha != null && ha.getSubmitted() == 0 )			
				   getActivity().getMenuInflater().inflate(R.menu.grid_img_act_context_full, menu);
				else
					getActivity().getMenuInflater().inflate(R.menu.grid_img_act_context, menu);
				
			}
			else
			{
				getActivity().getMenuInflater().inflate(R.menu.grid_img_act_context, menu);
			}
			
		}

		@Override
		public boolean onContextItemSelected(android.view.MenuItem item) {
			try
			{
				if(item.getItemId() == R.id.grid_img_cm_delete_img)		// delete img
				{							
					showDeleteImgConfirmDlg();
				}
				else if (item.getItemId() == R.id.grid_img_cm_send_to_server)  // send to server
				{
					UploadImageTask uploadTask = new UploadImageTask();
					Long chietTinhId = GlobalData.globalChietTinh.get_Id();
					
					String fileName = "";
				  
				    String imagePath = (String)mAdapter.getItem(mPos);
					
					String[] splitTexts = imagePath.split("/");
					
					fileName = splitTexts[splitTexts.length -1];
					
            		uploadTask.execute(fileName, GlobalData.globalChietTinh.get_Id() + "", GlobalData.globalChietTinh.get_MaBanChietTinh());
					
				}
			}
			catch(Exception e){
				e.printStackTrace();
				return false;
			}

			return true;
		}

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onActivityCreated(savedInstanceState);
						
			listener = new UpdateListener();
			
			try
			{
				// get the current date
				final Calendar c = Calendar.getInstance();
				mcur_Year = c.get(Calendar.YEAR);			
				mDay = c.get(Calendar.DAY_OF_MONTH);
				mMonth = c.get(Calendar.MONTH) + 1;
				mYear = c.get(Calendar.YEAR);				
			}
			catch(Exception e){}
			
			if(savedInstanceState == null)
			{
				loadImagesPathFromBD();
			}
			else
			{

			}
		}

		
		
		public void refreshImageGridView() {
			
			File folder = new File(folderPath);
			
			List<String> imageList = new ArrayList<String>(Arrays.asList(folder.list()));
			
			//clear the list and rebind data
			arrPathImgs.clear();
			
			for(int i = 0; i < GlobalData.HinhAnhList.size(); i++)
			{
				if(imageList.contains(GlobalData.HinhAnhList.get(i).getFilename()))
				{
					arrPathImgs.add(folderPath + "/" + GlobalData.HinhAnhList.get(i).getFilename());
				}
			}
			
			mAdapter.setItemList(arrPathImgs);
			mAdapter.notifyDataSetChanged();
			
		}
		
		
		
		TextView tvhint;
		
		public void loadImagesPathFromBD()
		{
			List<HinhAnhChiTietModel> entries = new ArrayList<HinhAnhChiTietModel>();

			GlobalData.HinhAnhList.clear();
			
			HinhAnhChiTietDataSource dbHelper = new HinhAnhChiTietDataSource();

			if(GlobalData.globalChietTinh != null && GlobalData.globalChietTinh.get_Id() > 0)
				entries = dbHelper.getHinhAnhChiTietByHoSoId(GlobalData.globalChietTinh.get_Id());
				
						
			arrPathImgs.clear();
			
			if (entries.size() > 0)
				tvhint.setText(getString(R.string.str_deleteHint));
			else
				tvhint.setText(getString(R.string.str_no_image));

			File folder = new File(folderPath);

			if(folder != null && folder.isDirectory() && folder.list().length > 0)
			{
				List<String> listPath = new ArrayList<String>(Arrays.asList(folder.list()));
								
				for(int i = 0; i < entries.size(); i++)
				{
					if(listPath.contains(entries.get(i).getFilename()))
					{
						GlobalData.HinhAnhList.add(entries.get(i));
						arrPathImgs.add(folderPath + "/" + entries.get(i).getFilename());
					}
				}
					
				mAdapter.setItemList(arrPathImgs);
				mAdapter.notifyDataSetChanged();
			}
			
		}
		

		
		@Override
		public void onResume() {
			super.onResume();
			mAdapter.notifyDataSetChanged();
			
			if (!UpdateListenerIsRegistered && listener != null) {
				IntentFilter intentFilter = new IntentFilter();
				intentFilter.addAction("com.application.chiettinhdienluc.ui.ImageGridCreateImgFolder");
				getActivity().registerReceiver(listener, intentFilter);
				UpdateListenerIsRegistered = true;
			}
		}
		
		@Override
		public void onPause() {
			super.onPause();
			if (UpdateListenerIsRegistered && listener != null) {
				getActivity().unregisterReceiver(listener);
				UpdateListenerIsRegistered = false;
			}
		}

		@TargetApi(VERSION_CODES.JELLY_BEAN)
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
			final Intent i = new Intent(getActivity(), ImageDetailActivity.class);
			i.putExtra(ImageDetailActivity.EXTRA_IMAGE, (int) id);
			if (Utils.hasJellyBean()) {
				// makeThumbnailScaleUpAnimation() looks kind of ugly here as the loading spinner may
				// show plus the thumbnail image in GridView is cropped. so using
				// makeScaleUpAnimation() instead.
				ActivityOptions options =
						ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight());
				getActivity().startActivity(i, options.toBundle());
			} else {
				startActivity(i);
			}
		}

		

		private class ImageAdapter extends BaseAdapter {

			private final Context mContext;
			private int mItemHeight = 0;
//			private int mNumColumns = 0;
			private int mActionBarHeight = 0;
			private GridView.LayoutParams mImageViewLayoutParams;
			private AQuery aq;
			
			private ArrayList<String> arrPaths = new ArrayList<String>();

			public ImageAdapter(Context context, AQuery aq, ArrayList<String> arrPaths) {
				super();
				mContext = context;
				this.aq = aq;
				this.arrPaths = arrPaths;
				mImageViewLayoutParams = new GridView.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
				// Calculate ActionBar height
				TypedValue tv = new TypedValue();
				if (context.getTheme().resolveAttribute(
						android.R.attr.actionBarSize, tv, true)) {
					mActionBarHeight = TypedValue.complexToDimensionPixelSize(
							tv.data, context.getResources().getDisplayMetrics());
					mActionBarHeight = 1;
				}
			}

			@Override
			public int getCount() {
				// If columns have yet to be determined, return no items
//				if (getNumColumns() == 0) {
//					return 0;
//				}

				// Size + number of columns for top empty row
//				return Images.imageThumbUrls.length + mNumColumns;
				return arrPaths.size();
			}
			
			public void setItemList(ArrayList<String> arrPaths)
			{
				this.arrPaths = arrPaths;
				
				if(this.arrPaths.size() > 0) {
					tvhint.setText(getString(R.string.str_deleteHint));
				}
				else
				{
					
					tvhint.setText(getString(R.string.str_no_image));
				}
				
			}
			
			public ArrayList<String> getItemList()
			{
				return this.arrPaths;
			}

			@Override
			public Object getItem(int position) {
//				return position < mNumColumns ? null : arrPaths.get(position - mNumColumns);
				return arrPaths.get(position);
			}

			@Override
			public long getItemId(int position) {
				return position;
			}

			@Override
			public int getViewTypeCount() {
				// Two types of views, the normal ImageView and the top row of empty views
				return 2;
			}

			@Override
			public int getItemViewType(int position) {
				return 0;
			}

			@Override
			public boolean hasStableIds() {
				return true;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup container) {
				//				 First check if this is the top row
//				if (position < mNumColumns) {
//					if (convertView == null) {
//						convertView = new View(mContext);
//					}
//					// Set empty view with height of ActionBar
//					convertView.setLayoutParams(new AbsListView.LayoutParams(
//							ViewGroup.LayoutParams.MATCH_PARENT, mActionBarHeight));
//					return convertView;
//				}

				// Now handle the main ImageView thumbnails
				ImageView imageView;
				if (convertView == null) { // if it's not recycled, instantiate and initialize
					imageView = new ImageView(mContext);
					imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
					imageView.setLayoutParams(mImageViewLayoutParams);
				} else { // Otherwise re-use the converted view
					imageView = (ImageView) convertView;
				}

				// Check the height matches our calculated column width
				if (imageView.getLayoutParams().height != mItemHeight) {
					imageView.setLayoutParams(mImageViewLayoutParams);
				}
				
//				imageView.setPadding(10, 10, 10, 10);
				
				// Finally load the image asynchronously into the ImageView, this also takes care of
				// setting a placeholder image while the background thread runs
				//				mImageFetcher.loadImage(Images.imageThumbUrls[position - mNumColumns], imageView);
				try {
					aq.id(imageView).image(arrPaths.get(position), ImageOptionsUtils.getImageOptionsGallery());
				} catch (Exception e) {
					// TODO: handle exception
				}

				return imageView;
			}

			/**
			 * Sets the item height. Useful for when we know the column width so the height can be set
			 * to match.
			 *
			 * @param height
			 */
			public void setItemHeight(int height) {
				if (height == mItemHeight) {
					return;
				}
				mItemHeight = height;
				mImageViewLayoutParams = new GridView.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
				notifyDataSetChanged();
			}

		}

		private int mPos;

		
		private void safeCloseDialog(Dialog dialog) {
			if (dialog!=null && dialog.isShowing()) dialog.dismiss();
		}
		
		private void showDeleteImgConfirmDlg() {
			try {
				com.application.chiettinhdienluc.dialog.ConfirmDialog.ConfirmBuilder builder = new ConfirmDialog.ConfirmBuilder(getActivity());
				builder.setTitle(R.string.str_dialog_confirm_title);
				builder.setMessage(R.string.str_dialog_confirm_delete_img_content);	
				
				builder.setPositiveButton(R.string.str_btn_ok, new DialogInterface.OnClickListener() {		
					@Override
					public void onClick(DialogInterface dialog, int which) {
						deletePicture();
						safeCloseDialog(mDialogDeleteImg);
					}					
				});
				
				
				builder.setNegativeButton(R.string.str_btn_close, new DialogInterface.OnClickListener() {				
					@Override
					public void onClick(DialogInterface dialog, int which) {
						safeCloseDialog(mDialogDeleteImg);			
					}
				});			
				
				mDialogDeleteImg = builder.create();
				mDialogDeleteImg.setCancelable(false);
				mDialogDeleteImg.show();
			} catch (Exception ex) {
				ex.printStackTrace();			
				safeCloseDialog(mDialogDeleteImg);			
			}
		}
		
		private void deletePicture()
		{
			try {
				if(mPos >= 0 && mPos < mAdapter.getCount())
				{
					String imagePath = (String)mAdapter.getItem(mPos);
					
					String[] splitTexts = imagePath.split("/");

					if(splitTexts.length > 0)// && (splitTexts[splitTexts.length - 1].endsWith(".JPG") || splitTexts[splitTexts.length - 1].endsWith(".JPEG")))
					{
						String ext = !TextUtils.isEmpty(splitTexts[splitTexts.length - 1]) ? splitTexts[splitTexts.length - 1].substring(splitTexts[splitTexts.length - 1].lastIndexOf(".")+1) : "";

						if(ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg"))
						{
							if(GlobalData.globalChietTinh.get_Id() > 0) {
								HinhAnhChiTietDataSource dbHelper = new HinhAnhChiTietDataSource();
								int numOfEffect = dbHelper.deleteImageByHoSoId(GlobalData.globalChietTinh.get_Id(), splitTexts[splitTexts.length - 1]);
								
								if(numOfEffect > 0)
								{
									Utils.showMess(getString(R.string.str_hint_msg_delete_img_success));
								}
								
								GlobalData.HinhAnhList.remove(mPos);
							}
							else
							{
								GlobalData.HinhAnhList.remove(mPos);								
							}
							
							arrPathImgs.remove(mPos);
							mAdapter.setItemList(arrPathImgs);
							mAdapter.notifyDataSetChanged();
							
							if(mAdapter.getCount() == 0)  {
								tvhint.setText(getString(R.string.str_no_image));
							}
							else
							{								
								tvhint.setText(getString(R.string.str_deleteHint));
							}
							
							
							File imgFile = new File(imagePath);
							
							if(imgFile != null && imgFile.isFile() && imgFile.exists())
							{
								boolean deleted = imgFile.delete();
							}
						}
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		
		protected class UploadImageTask extends AsyncTask<String, Void, Bundle> {		   
		    @Override
		    protected Bundle doInBackground(String...  ct) {
		    	
		    	String baseUrl = MainApplication.getServerURL();
		    	//http://192.168.1.46:46685
		    	String url = baseUrl + "/ctrs/resources/hosochiettinh";  
		    	    		
				NetClientPost poster = new NetClientPost(url);       
		       	
				String result = "fail";		
				
				result = poster.uploadHinhAnhHoSo(ct[0], ct[1], ct[2] );  
				
				Bundle output = new Bundle();
		        output.putString("file_name", ct[0]);
		        output.putString("result", result);
		        return output;	       
		    }

		    
		    String input; 
		    
		    @Override
		    protected void onPostExecute(Bundle bundle) {   	        	
		       
		        
		        String result = bundle.getString("result");
		        
		        Log.i("Upload result", result);
		        
		        if(result.equalsIgnoreCase("success")) {
		        	
		        	HinhAnhChiTietDataSource dataSource = new HinhAnhChiTietDataSource();
		        	
		        	dataSource.updateSumitted(bundle.getString("file_name"));
		        	
		        	loadImagesPathFromBD();
		        	
		        	Utils.showMess(getString(R.string.str_hint_msg_send_img_success));   		        	
		        }	    	
		    }

		    @Override
		    protected void onPreExecute() {
		       // Log.i(TAG, "onPreExecute");
		    	
		    }

		    @Override
		    protected void onProgressUpdate(Void... values) {
		        //Log.i(TAG, "onProgressInsert");
		    }
		}
		
		protected class UpdateListener extends BroadcastReceiver {
			@Override
			public void onReceive(Context context, Intent intent) {
				try {
					if(intent != null && !TextUtils.isEmpty(intent.getAction()))
					{
						String action = intent.getAction();
						
						if(!TextUtils.isEmpty(action))
						{
							if(action.equals("com.application.chiettinhdienluc.ui.ImageGridCreateImgFolder"))
							{ 								
								HinhAnhChiTietDataSource dbHelper = new HinhAnhChiTietDataSource();
								
								for(int i = 0; i < GlobalData.HinhAnhList.size(); i++)
								{

									if(GlobalData.globalChietTinh != null && GlobalData.globalChietTinh.get_Id() > 0)
									{
										if(GlobalData.HinhAnhList.get(i).getHosochiettinhid().equalsIgnoreCase("")) {
											GlobalData.HinhAnhList.get(i).setHosochiettinhid(GlobalData.globalChietTinh.get_Id() + "");
											long pos = dbHelper.addNewImageInfo( GlobalData.HinhAnhList.get(i));
											tvhint.setText(getString(R.string.str_deleteHint));	
										}
										
									}
								}
									
									//loadImagesPathFromBD();
								}							
						}	
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
	}	

	/**
	 * The main adapter that backs the GridView. This is fairly standard except the number of
	 * columns in the GridView is used to create a fake top row of empty views as we use a
	 * transparent ActionBar and don't want the real top row of images to start off covered by it.
	 */	
}







